package com.woniu.smallmedical.controller;

import com.woniu.smallmedical.entity.*;
import com.woniu.smallmedical.server.serverimpl.CostServerImpl;
import com.woniu.smallmedical.server.serverimpl.PatientInformationServerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@RestController
public class CostController {
    @Autowired
    CostServerImpl costServer;
    @Autowired
    PatientInformationServerImpl patientInformationServer;

    @GetMapping("/getOrderType")
    public ResponseResult<List<OrderType>> selectAllOrderType() {
        List<OrderType> allOrderType = costServer.getAllOrderType();
        return new ResponseResult<>(allOrderType, 200, "缴费类型");
    }

    @GetMapping("/getCosts")
    public ResponseResult<PageBean<Cost>> selectCosts(String costTimeStart,String costTimeEnd,
                                                      String patientnumber,String orderTypeId,int fid,
                                                      int pageIndex,int pageSize){
        Cost cost = new Cost();
        if (patientnumber!=null && !patientnumber.equals("")){
            PatientInformation patient = costServer.getPatientByNumber(Integer.parseInt(patientnumber));
            if (patient==null){
                return new ResponseResult<>(null, 201, "费用表无信息");
            }else {
                cost.setPatientId(patient);
            }
        }
        if (orderTypeId!=null && !orderTypeId.equals("")){
            OrderType orderType = new OrderType();
            int norderTypeId = Integer.parseInt(orderTypeId);
            orderType.setOrderTypeId(norderTypeId);
            cost.setOrderTypeId(orderType);
        }
        if (fid!=0){
            Flow flow = new Flow();
            flow.setFid(fid);
            cost.setPayStateId(flow);
        }

        List<Cost> allCost = costServer.getAllCost(cost, costTimeStart, costTimeEnd, pageIndex, pageSize);

        for (Cost cos:allCost) {
            int userId = cos.getPatientId().getOperator();
            User user = costServer.getUserById(userId);
            cos.setDocname(user.getUsername());
            Integer did = user.getDid();
            Department dep = costServer.getDepById(did);
            cos.setDname(dep.getDname());
        }

        PageBean<Cost> pageBean = new PageBean<>();
        pageBean.setPageBeanList(allCost);
        pageBean.setPageIndex(pageIndex);
        pageBean.setPageSize(pageSize);
        int totalRecord = costServer.getCostCount(cost, costTimeStart, costTimeEnd);
        pageBean.setTotalRecord(totalRecord);


        return new ResponseResult<>(pageBean, 200, "费用表信息");
    }


    @GetMapping("/getPatientAll/{prid}")
    public ResponseResult<Receptiontype> selectAllPatient(@PathVariable("prid") Integer prid){
        //患者的处方
        Prescription prescription = costServer.getByPrescriptionId(prid);
        //挂号Id
        int rid = prescription.getRid().getRid();
        //挂号信息
        Registration registration = costServer.getRegByPatId(rid);
        //就诊状态Id
        int receptiontypeid = registration.getReceptiontypeid();
        //患者就诊状态
        Receptiontype receptiontype = costServer.getReceptiontypeById(receptiontypeid);
        return new ResponseResult<>(receptiontype, 200, "接诊类型");
    }

    @GetMapping("/getPrescriptionDetailsAll/{prid}")
    public ResponseResult<List<PrescriptionDetails>> selectAllPrescriptionDetails(@PathVariable("prid") Integer prid){

        List<PrescriptionDetails> prescriptionDetailsList = getPrescriptionDetailsSum(prid);

        return new ResponseResult<>(prescriptionDetailsList, 200, "处方详情");
    }

    @PutMapping("/updatePayState/{prid}/{orderTypeId}")
    public void updateCostPayStateId(@PathVariable("prid") Integer prid, @PathVariable("orderTypeId")String orderTypeId){
        //修改缴费状态
        costServer.updatePayStateByPrid(prid);
        //添加缴费类型
        costServer.updateOrderType(prid, Integer.parseInt(orderTypeId));
        //查询处方详情
        List<PrescriptionDetails> prescriptionDetailsList = costServer.getPrescriptionDetailsById(prid);

        for (PrescriptionDetails pdList: prescriptionDetailsList){
            //药品数量
            Integer total = pdList.getTotal();
            //库存数量
            Integer count = pdList.getInid().getCount();
            //更新库存数量
            count-=total;
            //药品库存Id
            Integer inid = pdList.getInid().getInid();
            //修改更新
            costServer.updateInvenCountById(inid, count);
        }
        //添加缴费时间
        costServer.updateCostTime(prid, new Date());
        //添加付款方式
        Random random = new Random();
        int payMethodId = random.nextInt(4) + 1;
        costServer.updatePayId(payMethodId, prid);

    }

    @GetMapping("/insertCost")
    public void insertIntoNewCost(){
        //获取所有处方Id
        List<Prescription> allPrescription = costServer.getAllPrescription();

        for (Prescription pr:allPrescription) {
            Integer prid = pr.getPrid();
            //查询费用表的处方Id
            Cost costs = costServer.getCosts(prid);
            if (costs!=null){
                continue;
            }
            //通过处方Id查询患者Id
            Prescription prescription = costServer.getByPrescriptionId(prid);
            //通过挂号Id
            Registration registration = costServer.getRegByPatId(prescription.getRid().getRid());
            //患者Id
            int sickid = registration.getSickid();
            System.out.println(sickid);
            PatientInformation patientInformation = new PatientInformation();
            patientInformation.setPaid(sickid);
            //获取缴费状态
            PatientInformation patByPaid = patientInformationServer.getPatByPaid(sickid);
            int flowstatus = patByPaid.getFlowstatus();
            Flow flow = new Flow();
            flow.setFid(flowstatus);
            //生成缴费单号
            String orderNumber = costOrderNumber();
            //获取缴费总金额
            BigDecimal costTotalBigDecimal = new BigDecimal("0");
            List<PrescriptionDetails> prescriptionDetailsSum = getPrescriptionDetailsSum(prid);
            for (PrescriptionDetails pd:prescriptionDetailsSum) {
                BigDecimal SubtotalbigDecimal = new BigDecimal(pd.getSubtotal());
                //小计相加
                costTotalBigDecimal = costTotalBigDecimal.add(SubtotalbigDecimal);
            }
            //缴费总额
            double costTotal = costTotalBigDecimal.doubleValue();

            Cost cost = new Cost();
            cost.setOrderNumber(orderNumber);
            cost.setPatientId(patientInformation);
            cost.setCostTotal(costTotal);
            cost.setPrid(prid);
            cost.setPayStateId(flow);
            //新增缴费基本信息
            costServer.insertIntoCost(cost);
        }


    }




    /**
     * 获取32位uuid的缴费单号
     * @return
     */
    public String costOrderNumber(){
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }


    /**
     * 处方详情各药品的小计
     * @param prid
     * @return
     */
    public List<PrescriptionDetails> getPrescriptionDetailsSum(Integer prid){
        //查询处方详情
        List<PrescriptionDetails> prescriptionDetailsList = costServer.getPrescriptionDetailsById(prid);

        //计算总金额
        for (PrescriptionDetails pdList: prescriptionDetailsList) {
            //药品数量
            Integer total = pdList.getTotal();
            //药品单价
            Double retail = pdList.getBmid().getRetail();

            BigDecimal totalBigDecimal = new BigDecimal(total);
            BigDecimal retailBigDecimal = new BigDecimal(retail);
            //单一药品小计
            BigDecimal Subtotalmultiply = totalBigDecimal.multiply(retailBigDecimal);
            pdList.setSubtotal(Subtotalmultiply.doubleValue());
        }
        return prescriptionDetailsList;
    }



}
